package org.wyy.sample;

import org.apache.zookeeper.KeeperException;

import java.util.Random;

/**
 * @author mars
 * @date 2024/1/22
 **/
public class ZkSyncTest {
    public static void main(String[] args) throws InterruptedException {

      barrierTest("/bTest", "localhost", "2");

        // 放100个节点
        //queueTest("p",100);

        Thread.sleep(5000);
        // FIFO删除,模拟队列
        //queueTest("c",100);
    }

    public static void queueTest(String type, Integer queueNum) {
        Queue q = new Queue("localhost", "/app1");
        int i;

        if (type.equals("p")) {
            System.out.println("Producer");
            for (i = 0; i < queueNum; i++)
                try{
                    q.produce(10 + i);
                } catch (KeeperException e){

                } catch (InterruptedException e){

                }
        } else {
            System.out.println("Consumer");

            for (i = 0; i < queueNum; i++) {
                try{
                    int r = q.consume();
                    System.out.println("节点data: " + r);
                } catch (KeeperException e){
                    i--;
                } catch (InterruptedException e){
                }
            }
        }
    }

    /**
     * 模拟屏障
     * enter() 节点数达到num时,继续执行
     * leave() 节点数为0时,继续执行
     */
    public static void barrierTest(String root, String host, String num) {
        Barrier b = new Barrier(host, root, new Integer(num));
        try{
            // 自动创建一个节点后进入等待,等待加入其他节点
            boolean flag = b.enter();
            System.out.println("Entered barrier: " + num);
            if(!flag) System.out.println("Error when entering the barrier");
        } catch (Exception e){
            System.out.println(e);
        }


        try{
            // 自动删除一个节点后进入等待,等待删除剩余节点
            b.leave();
        } catch (Exception e){
            System.out.println(e);
        }
        System.out.println("Left barrier");
    }
}
